package jmind.core.pdf;

import com.google.common.collect.Lists;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * description:  pdf 转图片处理
 *
 * @author weibo.xie
 * @date : create in 12:31 上午 2020/3/12
 */
public class Pdf2Image {
    private static Logger logger = LoggerFactory.getLogger(Pdf2Image.class);

    /**
     * 根据pdf的页数生成图片
     * @param pdfFile
     * @param path  图片路径
     * @return
     */
    public static List<File> toImages(File pdfFile,String path){
        List<BufferedImage> picList = toBufferedImage(pdfFile,null);
        List<File> images=Lists.newArrayListWithExpectedSize(picList.size());
        for(int i=0;i<picList.size();i++){
            try {
                File file = new File(path + pdfFile.getName() + i + ".png");
                ImageIO.write(picList.get(i), "png", file);
                images.add(file);
            } catch (IOException e) {
                logger.error("",e);
            }
        }
        return images;
    }

    /**
     * pdf 多页转一张图片
     * @param pdfFile
     * @param outFile
     * @return
     */
    public static boolean toImage(File pdfFile, File outFile) {
        try {
            List<BufferedImage> picList = toBufferedImage(pdfFile,130/72f);
            BufferedImage bufferedImage = yPic(picList);
            ImageIO.write(bufferedImage, "png", outFile);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    public static boolean toImage(InputStream inputStream, File outFile) {
        try {
            List<BufferedImage> picList = toBufferedImage(PDDocument.load(inputStream),130/72f);
            BufferedImage bufferedImage = yPic(picList);
            ImageIO.write(bufferedImage, "png", outFile);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return false;
        }
    }

    public static List<BufferedImage> toBufferedImage(File pdfFile,Float scale){
        //获取去除后缀的文件路径
        try {
            PDDocument  doc = PDDocument.load(pdfFile);
            return toBufferedImage(doc,scale);
        } catch (IOException e) {
            logger.error("",e);
            return null;
        }
    }

    public static List<BufferedImage> toBufferedImage(PDDocument doc,Float scale){
        if(scale==null){
            scale=2.5f ;
        }
        List<BufferedImage> list = null;
        try {
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            list= Lists.newArrayListWithExpectedSize(pageCount);
            for(int i=0; i<pageCount; i++){
                //第二个参数越大生成图片分辨率越高，转换时间也就越长
                BufferedImage image = renderer.renderImage(i, scale);
                //   BufferedImage  image = renderer.renderImageWithDPI(i,130, ImageType.RGB);
                // File imageFile = File.createTempFile("temp",".png");
                //    ImageIO.write(image, "png", imageFile);
                list.add(image);
            }
        } catch (IOException e) {
            logger.error("", e);
        } finally {
            if (doc != null) {
                try {
                    //关闭文件,不然该pdf文件会一直被占用。
                    doc.close();
                } catch (IOException e) {
                    logger.error("", e);
                }
            }
        }
        return list;
    }
    /**
     * 纵向处理图片
     * @param picList
     */
    private static BufferedImage yPic(List<BufferedImage> picList) {
          // 总高度
            int height = 0,
                    // 总宽度
                    width = 0,
                    // 临时的高度 , 保存偏移高度
                    tempHeight = 0,
                    // 临时的高度，主要保存每个高度
                    tempEachHeight = 0,
                    // 图片的数量
                    picNum = picList.size();
            // 保存每个文件的高度
            int[] heightArray = new int[picNum];
            // 保存图片流
            BufferedImage buffer = null;
            // 保存所有的图片的RGB
            List<int[]> imgRGB = Lists.newArrayListWithExpectedSize(picNum);
            // 保存一张图片中的RGB数据
            int[] tempImageRGB;
            for (int i = 0; i < picNum; i++) {
                buffer = picList.get(i);
                // 图片高度
                heightArray[i] = tempHeight = buffer.getHeight();
                if (i == 0) {
                    // 图片宽度
                    width = buffer.getWidth();
                }
                // 获取总高度
                height += tempHeight;
                // 从图片中读取RGB
                tempImageRGB = new int[width * tempHeight];
                tempImageRGB = buffer.getRGB(0, 0, width, tempHeight, tempImageRGB, 0, width);
                imgRGB.add(tempImageRGB);
            }
            // 设置偏移高度为0
            tempHeight = 0;
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < picNum; i++) {
                tempEachHeight = heightArray[i];
                // 计算偏移高度
                if (i != 0) {
                    tempHeight += tempEachHeight;
                }
                // 写入流中
                imageResult.setRGB(0, tempHeight, width, tempEachHeight, imgRGB.get(i), 0, width);
            }
        return imageResult;
    }



}